<?php
date_default_timezone_set('Asia/Shanghai');

$script_php_dir = "/soooner/cam_upload_script/php/";

include_once($script_php_dir."include/mcrypt.php");

include_once($script_php_dir."UploadTimeAsc.php");

$request_log = "{$script_php_dir}log/{$LOG_DF}_report_error_file.log";

$ListenPath = $argv[1];
if(empty($ListenPath)){
	die("No xml file!\n");
}
$ListenPath = str_replace("\t","",str_replace("\n","",$ListenPath));

eachhRoot($ListenPath);

function eachhRoot($ListenPath=""){
	$script_delete=array();
	$script_fork=array();
	
	//遍历目录
	if(is_dir($ListenPath)){
		$roothandle = opendir($ListenPath);
		if($roothandle!==false){
			while(false!==($file = readdir($roothandle))){
                if($file!="."&&$file!=".."){
                    $filepath = $ListenPath.$file;
                    if(is_dir($filepath)){
						$camhandle = @opendir($filepath);
						if($camhandle!==false){			
							while(false!==($file2 = readdir($camhandle))){
								if($file2!="."&&$file2!=".."){
									$filepath2 = $filepath.'/'.$file2;
									if(is_dir($filepath2)){
										$evthandle = @opendir($filepath2);
										if($evthandle!==false){
											//删除异常文件
											if(strpos($file2,"timelength")!==false){
												$res = file_sort($filepath2,"end.evt",0);
												if($res){
													$temp_sub = explode("-",$res);
													$end_time = date("YmdHis",(strtotime($temp_sub[0])+1));
													if(time()-strtotime($end_time)>600){
														$script_delete[]=$filepath2;
													}
												}
											}else{											
												$res = file_sort($filepath2,"end.evt",0);
												$startres = file_sort($filepath2,"start.evt",1);
												$mp4res = file_sort($filepath2,".mp4.old",0);
												$flv = is_exist($filepath2,"flv");
												$idx = is_exist($filepath2,"idx");
												
												echo "\n";
												echo 's_file:'.$filepath2.'/'.$startres."\n";
												echo 'e_file:'.$filepath2.'/'.$res."\n";
												
												if($res){
													$temp_sub = explode("-",$res);
													$start_time = date("YmdHi",strtotime(str_replace("start.evt","",$startres)))."00";
													$end_time = date("YmdHis",(strtotime($temp_sub[0])+1));
													echo '+'.$start_time.'-',$end_time.'-',$res."\n";											
													if($mp4res){
														//删除已上传文件
														$mp4temp_sub = explode("-",$mp4res);
														$mp4start_time = $mp4temp_sub[0];
														$mp4end_time = str_replace(".mp4.old","",$mp4temp_sub[1]);
														echo "-".$mp4start_time.'-',$mp4end_time."\n";												
														if($start_time==$mp4start_time&&$end_time==$mp4end_time){
															if(time()-strtotime($end_time)>600){
																$script_delete[]=$filepath2;
															}
														}
													}else{											
														if($flv&&$idx){
															if(!dir_islock($filepath2)){
																dir_lock($filepath2);
															}else{
																remove_lock_oldtime($filepath2,120);
															}
															$script_fork[$filepath2]=array($filepath2,$file,$file2,$start_time,$end_time);															
														}
														else{															
															if(time()-strtotime($end_time)>600){
																$script_delete[]=$filepath2;																
															}
														}											
													}
												}
											}											
										}										
									}
								}
							}
						}
					}
				}
			}
		}
		closedir($roothandle);
	}
	
	$uploadurl=array();
	$t_url = "http://t.auto.soooner.com/getserver";
	$t_data['obdid'] = 1;
	$t_data['stype'] = 11;
	$t_data['token'] = 1;
	$msg = json_decode(uploadByCURL(json_encode($t_data),$t_url),true);
	if($msg['result']!=0){
		global $request_log;
		$logRequest = fopen($request_log,"a");
		fwrite($logRequest,date("Y-m-d H:i:s")."$msg['uploadurl']".json_encode($t_data)."\n");
		fclose($logRequest);
		die;
	}
	$uploadurl[0] = $msg['uploadurl'];
	//特殊处理可视路况的视频
	$t_data['stype'] = 10;
	$msg = json_decode(uploadByCURL(json_encode($t_data),$t_url),true);
	if($msg['result']!=0){
		global $request_log;
		$logRequest = fopen($request_log,"a");
		fwrite($logRequest,date("Y-m-d H:i:s")."$msg['uploadurl']".json_encode($t_data)."\n");
		fclose($logRequest);
		die;
	}
	$uploadurl[1] = $msg['uploadurl'];
	
	if($script_fork){
		$count = 0;		
		foreach($script_fork as $cmd){
			$pid=pcntl_fork();
			if($pid==-1){
				exit(-1);
			}else if($pid){
				$count++;
			}else{
				uploadHandle($cmd[0],$cmd[1],$cmd[2],$cmd[3],$cmd[4],$uploadurl);
				dir_unlock($cmd[0]);
				exit(0);
			}
		}
		while(true){ 
			if($count==0){
				break;
			}
			pcntl_wait($status);
			$count--;	
		}		
	}	
	
	if($script_delete){
		foreach($script_delete as $file){
			rm_file($file);
		}
	}	
}

//Public-CURL-POST
function uploadByCURL($post_data,$post_url){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30 );
	curl_setopt($curl, CURLOPT_TIMEOUT, 60 );
	curl_setopt($curl, CURLOPT_URL, $post_url);
	curl_setopt($curl, CURLOPT_LOW_SPEED_LIMIT, 102400);
	curl_setopt($curl, CURLOPT_POST, 1 );
	curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0");
	$result = curl_exec($curl);
	$error = curl_error($curl);
	curl_close($curl);
	return $error ? $error : $result;
}				

//lock file
function dir_lock($path){
	if(file_exists($path)){
		$path .= "/lock";
		$fp = fopen($path,"a");
        $r=fwrite($fp,date("Y-m-d H:i:s")."\n");
		fclose($fp);
	}	
}

//Delete files overtime
function remove_lock_oldtime($path,$lock_max_time){
	if(file_exists($path)){
		$path .= "/lock";
		if(file_exists($path)){
			$tmp_time = strtotime(file_get_contents($path));
			if((time()-$tmp_time)>$lock_max_time){
				unlink($path);
			}
		}		
	}
}

//unlock file
function dir_unlock($path){
    if(file_exists($path)){
        $path .= "/lock";
        if(file_exists($path)){
            unlink($path);
        }
    }
}

//determine whether to lock 
function dir_islock($path){
	if(file_exists($path)){
		$path .= "/lock";
		return file_exists($path);
	}
}

//sort the file according to the time 
function file_sort($file,$string,$sort){
	$array_key=array();
	$array_value=array();
	$array_file=scandir($file);
	foreach($array_file as $path){
		if(strpos($path,"$string")!==false){
			$filepath = $file.'/'.$path;
			$file_time=filemtime($filepath);
			$array_key[]=$file_time;
			$array_value[$file_time]=$path;
		}
	}
	if(empty($array_value)==false){
		if($sort){
			sort($array_key);
		}else{
			rsort($array_key);
		}
		return $array_value[$array_key[0]];
	}else{
		return false;
	}
}

//determine whether exist
function is_exist($file,$string){
	$array_file = scandir($file);
	$a = 0;
	foreach($array_file as $path){
		if(strpos($path,"$string")){
			$a=1;
			break;
		}
	}
	return $a;
}

//detele directory
function rm_file($file){
	if(is_dir($file)){
		$handle=opendir($file);
		while(($path=readdir($handle))!==false){
			if($path!="."&&$path!=".."){
				$filepath=$file."/".$path;
				if(!is_dir($filepath)){
					unlink($filepath);
				}
				else{
					rm_file($filepath);
				}
			}
		}
		closedir($handle);
		rmdir($file);
	}
}
?>	